/*
 *  All rights reserved 
 *  Naive Coders
 */
package com.naivecoders.refex;

import com.naivecoders.refex.functions.AbstractFunction;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Andrii_Butenko
 */
public class CallTrail {

    private List<TrailEntry> trail;

    public void startTrail() {
        trail = new ArrayList<>();
    }

    public void endTrail() {
        trail = null;
    }

    public void registerCall(AbstractFunction func, AbstractFunction res) {
        if (trail != null) {
            trail.add(new TrailEntry(func, res));
        }
    }
 
    public CallTrailState snapshotState() {
        return new CallTrailState(trail);
    }

    private static class TrailEntry {

        private final AbstractFunction function;
        private final AbstractFunction result;

        public TrailEntry(AbstractFunction function, AbstractFunction result) {
            this.function = function;
            this.result = result;
        }

        @Override
        public String toString() {
            return String.format("%s\t->\t%s", function, result);
        }
    }

    public static class CallTrailState {

        private List<TrailEntry> trailCopy;

        private CallTrailState(List<TrailEntry> tr) {
            this.trailCopy = new ArrayList<>(tr);
        }

        public void dump(PrintStream ps) {
            for (TrailEntry te : trailCopy) {
                ps.print("\t");
                ps.println(te);
            }
        }
    }
}
